//
//  LLRefreshNomalFooter.m
//  PandaMakeUp
//
//  Created by dl on 16/1/13.
//  Copyright © 2016年 lrlz. All rights reserved.
//

#import "LLRefreshNomalFooter.h"
#import "LLLoadingFooterView.h"
#import "LLRefreshComponent.h"
#import "UIScrollView+LLRefresh.h"
#import "LLRefreshConst.h"

#define LLRefreshNomalFooterHeight           40

@interface LLRefreshNomalFooter ()
@property(nonatomic, weak) LLLoadingFooterView *footerView;
@property(nonatomic, assign) BOOL readyToRefresh;
@end

@implementation LLRefreshNomalFooter {
    __weak LLLoadingFooterView *_footerView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _readyToRefresh = NO;
    }
    return self;
}

+ (instancetype)footerWithRefreshingBlock:(LLRefreshComponentRefreshingBlock)refreshingBlock {
    LLRefreshNomalFooter *cmp = [[self alloc] init];
    cmp.refreshingBlock = refreshingBlock;
    return cmp;
}

- (LLLoadingFooterView *)footerView {
    if (!_footerView) {
        LLLoadingFooterView *footerView = [[LLLoadingFooterView alloc] initWithFrame:CGRectMake(0, 0, 0, LLRefreshNomalFooterHeight)];
        [self addSubview:_footerView = footerView];
    }
    return _footerView;
}

#pragma mark - 覆盖父类的方法

- (void)prepare {
    [super prepare];

    self.ll_height = LLRefreshNomalFooterHeight;
    self.layer.masksToBounds = YES;

    UIEdgeInsets insets = self.scrollView.contentInset;
    insets.bottom = insets.bottom + self.ll_height;
    self.scrollView.contentInset = insets;
}

- (void)placeSubviews {
    [super placeSubviews];

    // 设置y值(当自己的高度发生改变了，肯定要重新调整Y值，所以放到placeSubviews方法中设置y值)
    self.ll_top = self.scrollView.contentSize.height;
    self.footerView.ll_width = self.ll_width;
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];

    if (newSuperview) {
        // 监听scrollView数据的变化
        [self.scrollView setReloadDataBlock:^(NSInteger totalDataCount) {
            self.hidden = (totalDataCount == 0);
        }];
    }
}

- (void)scrollViewContentSizeDidChange:(NSDictionary *)change {
    [super scrollViewContentSizeDidChange:change];

    // 设置位置
    self.ll_top = self.scrollView.contentSize.height;
}

- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change {
    [super scrollViewContentOffsetDidChange:change];

    if (self.state != LLRefreshStateIdle
            || self.state == LLRefreshStateNoMoreData
            || self.ll_top == 0
            || !_readyToRefresh)
        return;

    if (_scrollView.contentInset.top + _scrollView.contentSize.height > _scrollView.ll_height) { // 内容超过一个屏幕
        if (_scrollView.contentOffset.y >= _scrollView.contentSize.height - _scrollView.ll_height + self.ll_height + _scrollView.contentInset.bottom - self.ll_height) {
            // 防止手松开时连续调用
            CGPoint old = [change[@"old"] CGPointValue];
            CGPoint new = [change[@"new"] CGPointValue];
            if (new.y <= old.y) return;

            // 当底部刷新控件完全出现时，才刷新
            [self beginRefreshing];
        }
    }
}

- (void)scrollViewPanStateDidChange:(NSDictionary *)change {
    [super scrollViewPanStateDidChange:change];

    if ([change[@"new"] integerValue] == UIGestureRecognizerStateBegan) {
        _readyToRefresh = YES;
    }

    if (self.state != LLRefreshStateIdle
            || self.state == LLRefreshStateNoMoreData
            || !_readyToRefresh)
        return;

    if (_scrollView.panGestureRecognizer.state == UIGestureRecognizerStateEnded) {// 手松开
        if (_scrollView.contentInset.top + _scrollView.contentSize.height <= _scrollView.ll_height) {  // 不够一个屏幕
            if (_scrollView.contentOffset.y >= -_scrollView.contentInset.top) { // 向上拽
                [self beginRefreshing];
            }
        }
        else { // 超出一个屏幕
            if (_scrollView.contentOffset.y >= _scrollView.contentSize.height + _scrollView.contentInset.bottom - _scrollView.ll_height) {
                [self beginRefreshing];
            }
        }
    }
}

- (void)setState:(LLRefreshState)state {
    LLRefreshCheckState

    if (state == LLRefreshStateRefreshing) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self executeRefreshingCallback];
        });
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.footerView.state = state;
    });
}

- (void)beginRefreshing {
    _readyToRefresh = NO;
    [super beginRefreshing];
}

- (void)setHidden:(BOOL)hidden {
    BOOL lastHidden = self.isHidden;

    [super setHidden:hidden];

    UIEdgeInsets insets = self.scrollViewOriginalInset;
    if (!lastHidden && hidden) {
        self.state = LLRefreshStateIdle;

        insets.bottom = insets.bottom - self.ll_height;
        self.scrollView.contentInset = insets;
    } else if (lastHidden && !hidden) {
        insets.bottom = insets.bottom + self.ll_height;
        self.scrollView.contentInset = insets;

        // 设置位置
        self.ll_top = _scrollView.contentSize.height;
    }
}

#pragma mark - 公共方法

- (void)noticeNoMoreData {
    self.state = LLRefreshStateNoMoreData;
}

- (void)resetNoMoreData {
    self.state = LLRefreshStateIdle;
}

@end
